#!/usr/bin/bash

#============================================
# Nginx日志分析
# 参考：https://www.imooc.com/video/10899
#============================================

clear
#初始化终端颜色，即清除颜色
resetTerminal=$(tput sgr0)
GREEN='\e[1;32m' #绿
RED='\e[1;31m'  #红
 
logFilePath="../public/file/access.log"

#状态码分类统计分析
function checkHttpStatus()
{    
    echo '------------- 状态码分类统计 -------------'
    arrHttpStatuCode=(`cat $logFilePath | grep -ioE "HTTP\/1\.[1|0]\"[[:blank:]][0-9]{3}" | awk -F"[ ]+" '{    
            if($2>100 && $2<200) 
                {i++}    
            else if($2>=200 && $2<300)
                {j++}
            else if($2>=300 && $2<400)
                {k++}    
            else if($2>=400 && $2<500)
                {n++}    
            else if($2>=500)
                {p++}    
            } END {print i?i:0, j?j:0, k?k:0, n?n:0, p?p:0, i+j+k+n+p}'
		`)    

    echo -e "${GREEN}状态码为100~200的日志数:$resetTerminal" ${arrHttpStatuCode[0]}  
    echo -e "${GREEN}状态码为200~300的日志数:$resetTerminal" ${arrHttpStatuCode[1]}  
    echo -e "${GREEN}状态码为300~400的日志数:$resetTerminal" ${arrHttpStatuCode[2]}  
    echo -e "${GREEN}状态码为400~500的日志数:$resetTerminal" ${arrHttpStatuCode[3]}  
    echo -e "${GREEN}状态码为500以上的日志数:$resetTerminal" ${arrHttpStatuCode[4]}  
    echo -e "${GREEN}所有状态码的日志数总计:$resetTerminal" ${arrHttpStatuCode[5]}  
}    

#错误状态码统计分析
function checkHttpCode()
{   
    echo '------------- 错误码分类统计 -------------'
    httpCode=(`cat $logFilePath | grep -ioE "HTTP\/1\.[1|0]\"[[:blank:]][0-9]{3}" | awk -v total=0 -F '[ ]+' '{
                if ($2 != "") {
                    code[$2]++
                    total++
                } else {
                    exit
                }    
            } END {print code[304]?code[304]:0, code[404]?code[404]:0, code[403]?code[403]:0, total    
	     }'    

	 `)    

    echo -e "${GREEN}状态码为304的日志数:$resetTerminal" ${Http_Code[0]}    
    echo -e "${GREEN}状态码为404的日志数:$resetTerminal" ${Http_Code[1]}    
    echo -e "${GREEN}状态码为403的日志数:$resetTerminal" ${Http_Code[2]}    
    echo -e "${GREEN}所有错误日志数总计:$resetTerminal" ${Http_Code[3]}    
}    

# 按IP访问次数降序排列
# cat $logFilePath | awk '{print $1}' | sort | uniq -c | sort -rn | more
function showIpList()
{
    echo '------------- 访客PV降序排列 -------------'
    cat $logFilePath | awk '{print $1}' | sort | uniq -c | sort -rn 
}

checkHttpStatus
checkHttpCode    
showIpList

